package www.com.library.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.inputmethod.EditorInfo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import www.com.common.library.R;
import www.com.library.app.Logger;
import www.com.library.util.DoubleConverter;
import www.com.library.util.ProductPrecision;

/**
 * 价格输入框基础类
 */
public class NumberInput2 extends android.support.v7.widget.AppCompatEditText {

    public static final int MAX_NUM_OF_INTEGERS = 7;
    private int mMaxDigitBeforeDot = MAX_NUM_OF_INTEGERS;
    private int mMaxDecimalDigit = 2;  //小数位数
    private float mMultipleSteps = 5; //最大调整数
    private double mMinStep = 0.01f; //最小调整数
    private double mMax = Double.MAX_VALUE;
    private double mMin = Double.MIN_VALUE;
    private String suffixStr = "";
    private String mDefalutValue = "";

    public NumberInput2(Context context) {
        super(context);
        init();
    }

    public NumberInput2(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public NumberInput2(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    /**
     * 设置输入框内输入数字的范围
     */
    public void setDigits(int maxlength, int beforeDot, int afterDot) {
        mMaxDigitBeforeDot = beforeDot;
        mMaxDecimalDigit = afterDot;
        this.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxlength), new DecimalDigitsInputFilter(beforeDot, afterDot)});
    }

    /**
     * 设置后缀值
     */
    public void setSuffixStr(String str) {
        suffixStr = str;
    }

    /**
     * 设置默认值
     */
    public void setDefalutValue(String value) {
        mDefalutValue = value;
    }

    /**
     */
    public void setDecimalDigits(int decimalPoint) {
        setDigits(MAX_NUM_OF_INTEGERS, MAX_NUM_OF_INTEGERS, decimalPoint);
    }

    public void setMin(double min) {
        mMin = min;
    }

    public void setMax(double max) {
        mMax = max;
    }

    public boolean isMinValue() {
        return !TextUtils.isEmpty(getText()) && getValue() <= mMin;
    }

    public boolean isMaxValue() {
        return !TextUtils.isEmpty(getText()) && getValue() >= mMax;
    }

    public void setMinSteps(double step) {
        mMinStep = step;
    }

    public void setMultipleSteps(int multiple) {
        mMultipleSteps = multiple;
    }

    /**
     * doule类型转换成string类型
     */
    public String valueToString(double value) {
        ProductPrecision precision = new ProductPrecision(mMaxDecimalDigit);
//		Logger.e("valueToString = " + value + ", " + precision.format(value));
        return precision.format(value);
    }

    /**
     * 返回double类型数值
     */
    public double getValue() {
        String value = getValueString();
        return DoubleConverter.toDoubleData(value);
    }

    /**
     * 返回点数值
     */
    public int getIntValue() {
        String value = getValueString();
        return DoubleConverter.toIntData(value);
    }

    /**
     * 返回float点数值
     */
    public Float getFloatValue() {
        String value = getValueString();
        return Float.valueOf(value);
    }

    /**
     * 返回str类型数据
     */
    public String getStrValue() {
        return getText().toString();
    }

    public String getValueString() {
        //处理整数时后面加“点”的情况
        String value = getText().toString();
        if (value.length() > 0 && !value.equals(".")) {
            if (value.contains(getContext().getResources().getString(R.string.order_title_suff))) {
                value = value.substring(0, value.length() - 1);
            }
        } else {
            value = "0";
        }
        return value;
    }

    /**
     * 止损止盈选项输入框值处理
     */
    public String getTextValue() {
        //处理整数时后面加“点”的情况
        String value = getText().toString();
        if (value.contains(getContext().getResources().getString(R.string.order_title_suff))) {
            value = value.substring(0, value.length() - 1);
        }
        return value;
    }

    /**
     * 止损止盈选项，判断输入框是否输入空值
     */
    public boolean isEmpty() {
        String value = getText().toString();
        return value.equals("");
    }

    /**
     * 止损止盈选项，判断输入框是否输入空值或者0
     */
    public boolean isEmptyOrZero(int digit) {
        String value = getText().toString();
        if (value.length() > 0 && !value.equals(".")) {
            return DoubleConverter.isEqual(DoubleConverter.toFloatData(getTextValue()), 0, digit);
        }
        return true;
    }

    /**
     * 判断是否为0，0返回true，否则返回false
     */
    private boolean checkzero() {
        final Double beforeValue = getValue();
        return beforeValue == 0.0;
    }

    /**
     * 检查价格范围值
     */
    private double checkRange(double value) {
        if (value > mMax)
            value = mMax;
        else if (value < mMin)
            value = mMin;

        return value;
    }

    /**
     * 按最小幅度增加价格值
     */
    public void incMinSteps() {
        if (checkzero()) {
            if (mMin == Double.MIN_VALUE) {
                setTextValue(mDefalutValue);
                Logger.e("mDefalutValue = " + mDefalutValue);
                return;
            } else {
                if (!DoubleConverter.isEqual(mMin, 0, 2)) {
                    setTextValue(valueToString(mMin));
                    return;
                }
            }
        }

        Double curValue = getValue();
        curValue += mMinStep;
        curValue = checkRange(curValue);
        setTextValue(valueToString(curValue));
    }

    /**
     * 按最小幅度减少价格值
     */
    public void decMinSteps() {
        if (checkzero()) {
            if (mMin == Double.MIN_VALUE) {
                setTextValue(mDefalutValue);
            } else {
                setTextValue(valueToString(mMin));
            }
            return;
        }

        Double curValue = getValue();
        curValue -= mMinStep;
        curValue = checkRange(curValue);
        setTextValue(valueToString(curValue));
    }

    /**
     * 按最大幅度增加价格值
     */
    public void incMultipleSteps() {
        Double curValue = getValue();
        curValue += (mMinStep * mMultipleSteps);
        curValue = checkRange(curValue);
        setTextValue(valueToString(curValue));
    }

    /**
     * 按最大幅度减少价格值
     */
    public void decMultipleSteps() {
        if (checkzero()) {
            setTextValue(valueToString(mMin));
            return;
        }

        Double curValue = getValue();
        curValue -= (mMinStep * mMultipleSteps);
        curValue = checkRange(curValue);
        setTextValue(valueToString(curValue));
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    void init() {
        setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        setTextValue("");
        setDigits(MAX_NUM_OF_INTEGERS, mMaxDigitBeforeDot, mMaxDecimalDigit);
        setGravity(Gravity.CENTER);
        setCursorVisible(true);
        setImeOptions(EditorInfo.IME_FLAG_NO_FULLSCREEN | EditorInfo.IME_ACTION_NONE);
    }

    /**
     * 设置控件不可操作
     */
    public void disabledWithText(String text) {
        setEnabled(false);
        setTextValue(text);
    }

    /**
     * 设置值
     */
    public void setTextValue(String text) {
        text = text + suffixStr;
        setText(text);
    }

    /**
     *
     */
    public void setEnabled(boolean enabled, boolean disableBackground) {
        if (enabled) {
            setDigits(MAX_NUM_OF_INTEGERS, mMaxDigitBeforeDot, mMaxDecimalDigit);
        } else {
            if (disableBackground) {
                setBackgroundColor(Color.TRANSPARENT);
                setGravity(Gravity.CENTER);
            }
        }

        super.setEnabled(enabled);
    }

    @Override
    public void setEnabled(boolean enabled) {
        setEnabled(enabled, true);
    }

    public void moveCursor2End() {
        if (hasFocus()) {
            setSelection(length());
        }
    }

    /**
     * 价格过滤器，使用正则表达式确定输入格式
     *
     * @author Administrator
     */
    public final class DecimalDigitsInputFilter implements InputFilter {

        Pattern mPattern;

        /**
         * @param digitsBeforeZero 整数位数
         * @param digitsAfterZero  小数位数
         */
        private DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
            //处理整数时后面加“点”的情况
            if (0 == digitsAfterZero) {
                mPattern = Pattern.compile("[0-9]{0," + digitsBeforeZero + "}");
            } else {
                mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero)
                        + "}+((\\.[0-9]{0," + (digitsAfterZero) + "})?)||(\\.)?");
            }
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            String ret = dest.subSequence(0, dstart).toString() + source.toString() + dest.subSequence(dend, dest.length());
            Matcher matcher = mPattern.matcher(ret);
            if (!matcher.matches())
                return "";
            return null;
        }

    }
}
